<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { useRoute, useRouter } from 'vue-router';
import axios from 'axios';
import RatingStars from '../components/RatingStars.vue';
import DoctorQA from '../components/DoctorQA.vue';
import { jwtDecode } from 'jwt-decode';
import { ElMessage } from 'element-plus';

const route = useRoute();
const router = useRouter();
const doctor = ref(null);
const isFollowing = ref(false);
const showLoginModal = ref(false);

const toggleFollow = () => {
    isFollowing.value = !isFollowing.value;
};

const maskUsername = (username: string) => {
    if (!username) return '';
    if (username.length <= 4) return username;
    return username.slice(0, 2) + '***' + username.slice(-2);
};

const formatDate = (dateString: string) => {
    const date = new Date(dateString);
    const month = date.getMonth() + 1;
    const day = date.getDate();
    const hours = date.getHours().toString().padStart(2, '0');
    const minutes = date.getMinutes().toString().padStart(2, '0');
    return `${month}月${day}日 ${hours}:${minutes}`;
};
const doctorId = route.params.doctorId;
const fetchDoctorDetails = async () => {
    

    if (!doctorId) {
        router.push('/');
        return;
    }

    try {
        const response = await axios.get(`http://127.0.0.1:8000/doctor/docdetail/${doctorId}/`);
        doctor.value = response.data;
    } catch (error) {
        console.error('Error fetching doctor details:', error);
        router.push('/');
    }
};

const goToLogin = () => {
    const redirecturl = router.currentRoute.value.fullPath;
    router.push({ name: 'Login', query: { redirecturl: redirecturl } });
};

const closeModal = () => {
    showLoginModal.value = false;
};


const submit = async () => {
    const token = localStorage.getItem('token');
    try {
        const decodedToken = jwtDecode(token);
        if (!decodedToken?.username) throw new Error('Token invalid');

        // 用户已登录，跳转到 Chat-Q 页面
        localStorage.removeItem('doctorId');
        localStorage.setItem('doctorId', doctorId); // 存储医生 ID 到本地存储
        router.push('/chat-Q');
    } catch (error) {
        ElMessage.warning('请先登录');
        showLoginModal.value = true; // 显示登录弹窗
    }
};

onMounted(() => {
    fetchDoctorDetails();
});
</script>

<template>
    <div v-if="doctor" class="doctor-detail">
        <!-- Header Section -->
        <div class="header-section">
            <img :src="doctor.avatar" :alt="doctor.name" class="doctor-avatar">
            <div class="doctor-info">
                <h1 class="doctor-name">{{ doctor.name }}</h1>
                <button class="follow-button" :class="{ 'following': isFollowing }" @click="toggleFollow">
                    {{ isFollowing ? '已关注' : '关注' }}
                </button>
            </div>
        </div>

        <!-- Professional Info -->
        <div class="professional-info">
            <div class="info-row">
                <span>{{ doctor.department }}</span>
                <span class="separator">|</span>
                <span>{{ doctor.get_title_display }}</span>
            </div>
            <div class="info-row">
                <span class="hospital-level">{{ doctor.hospital_level }}</span>
                <span>{{ doctor.hospital_name }}</span>
            </div>
            <div class="info-row" v-html="doctor.introduction"></div>
        </div>

        <!-- Rating Section -->
        <div class="rating-section">
            <div class="rating-row">
                <div class="rating-group">
                    <RatingStars :score="doctor.rating" size="1.2em" />
                    <span class="rating">{{ doctor.rating }}</span>
                </div>
                <div class="stat-group">
                    <span class="stat-value">{{ doctor.avg_response_time }}</span>
                    <span class="stat-label">分钟 内回应</span>
                </div>
                <div class="stat-group">
                    <span class="stat-value">{{ doctor.consultation_count }}</span>
                    <span class="stat-label">月问诊</span>
                </div>
                <div class="stat-group">
                    <span class="stat-value">{{ doctor.total_patients || 110 }}</span>
                    <span class="stat-label">月处方</span>
                </div>
            </div>
        </div>

        <!-- Specialty Section -->
        <div class="specialty-section">
            <h2>擅长方向</h2>
            <div class="specialty-content" v-html="doctor.specialty"></div>
        </div>

        <!-- Q&A Section -->
        <DoctorQA :doctorId="route.params.doctorId" />

        <!-- Patient Reviews -->
        <div class="reviews-section">
            <h2>患者评价</h2>
            <div v-for="evaluation in doctor.evaluations" :key="evaluation.id" class="review-item">
                <div class="review-header">
                    <div class="reviewer-info">
                        <span class="reviewer-name">{{ maskUsername(evaluation.user) }}</span>
                        <div class="rating-info">
                            <RatingStars :score="evaluation.score" />
                            <span class="review-score">{{ evaluation.score }}分</span>
                        </div>
                    </div>

                </div>
                <div class="review-content" v-html="evaluation.content"></div>
                <span class="review-date">{{ formatDate(evaluation.created_time) }}</span>
            </div>
        </div>

        <!-- Consultation Button -->
        <div class="consultation-button-container">
            <button class="consultation-button" @click="submit(doctorTd)">
                向{{ doctor.name }}医生提问 (￥{{ doctor.consultation_price }})
            </button>
        </div>
    </div>
    <div v-else class="loading">
        加载中...
    </div>
<!-- 弹框 -->
    <div v-if="showLoginModal" class="login-modal">
        <div class="modal-content">
            <p>您尚未登录，请先登录后再提问。</p>
            <div class="modal-actions">
                <button class="login-button" @click="goToLogin">去登录</button>
                <button class="cancel-button" @click="closeModal">取消</button>
            </div>
        </div>
    </div>


</template>

<style scoped>
.loading {
    text-align: center;
    padding: 40px;
    color: #666;
}

.doctor-detail {
    padding: 20px;
    max-width: 800px;
    margin: 0 auto;
    background: #fff;
}

.header-section {
    display: flex;
    align-items: center;
    margin-bottom: 24px;
}

.doctor-avatar {
    width: 120px;
    height: 120px;
    border-radius: 50%;
    object-fit: cover;
    margin-right: 24px;
}

.doctor-info {
    flex: 1;
}

.doctor-name {
    font-size: 24px;
    font-weight: bold;
    margin-bottom: 12px;
}

.follow-button {
    padding: 8px 24px;
    border-radius: 20px;
    border: 1px solid #00b38a;
    background: white;
    color: #00b38a;
    cursor: pointer;
    transition: all 0.3s ease;
}

.follow-button.following {
    background: #00b38a;
    color: white;
}

.professional-info {
    margin-bottom: 24px;
}

.info-row {
    display: flex;
    align-items: center;
    margin-bottom: 8px;
    color: #666;
}

.separator {
    margin: 0 8px;
    color: #ddd;
}

.hospital-level {
    background: #f5f5f5;
    padding: 2px 8px;
    border-radius: 4px;
    margin-right: 8px;
}

.rating-section {
    margin-bottom: 24px;
    padding: 16px 0;
}

.rating-row {
    display: flex;
    align-items: center;
    gap: 32px;
}

.rating-group {
    display: flex;
    align-items: center;
    gap: 8px;
}

.rating {
    font-size: 24px;
    font-weight: bold;
    color: #ffb800;
}

.stat-group {
    display: flex;
    align-items: baseline;
    gap: 4px;
}

.stat-value {
    font-size: 24px;
    font-weight: bold;
    color: #333;
}

.stat-label {
    font-size: 14px;
    color: #666;
}

.response-time,
.consultation-count {
    color: #666;
}

.specialty-section {
    margin-bottom: 24px;
}

.specialty-section h2 {
    font-size: 18px;
    margin-bottom: 16px;
}

.specialty-content {
    color: #666;
    line-height: 1.6;
}

.reviews-section {
    margin-bottom: 80px;
}

.reviews-section h2 {
    font-size: 18px;
    margin-bottom: 16px;
}

.review-item {
    padding: 16px 0;
    border-bottom: 1px solid #f0f0f0;
}

.review-header {
    margin-bottom: 8px;
}

.reviewer-info {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 4px;
}

.reviewer-name {
    color: #666;
    font-weight: 500;
}

.rating-info {
    display: flex;
    align-items: center;
    gap: 8px;
}

.review-score {
    color: #ffb800;
    font-weight: bold;
}

.review-date {
    color: #999;
    font-size: 0.9em;
}

.review-content {
    color: #333;
    line-height: 1.6;
}

.consultation-button-container {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
    padding: 16px;
    background: white;
    box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
}

.consultation-button {
    width: 100%;
    max-width: 800px;
    margin: 0 auto;
    display: block;
    padding: 16px;
    background: #00b38a;
    color: white;
    border: none;
    border-radius: 8px;
    font-size: 16px;
    cursor: pointer;
    transition: background 0.3s ease;
}

.consultation-button:hover {
    background: #009b76;
}

/* 登录弹框 */
.login-modal {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0, 0, 0, 0.5);
    display: flex;
    align-items: center;
    justify-content: center;
    z-index: 1000;
}

.modal-content {
    background: white;
    padding: 20px;
    border-radius: 8px;
    text-align: center;
    max-width: 300px;
    width: 80%;
}

.modal-actions {
    display: flex;
    justify-content: space-around;
    margin-top: 20px;
}

.login-button,
.cancel-button {
    padding: 10px 20px;
    border: none;
    border-radius: 4px;
    cursor: pointer;
    transition: background 0.3s ease;
}

.login-button {
    background: #00b38a;
    color: white;
}

.login-button:hover {
    background: #009b76;
}

.cancel-button {
    background: #f5f5f5;
    color: #333;
}

.cancel-button:hover {
    background: #ddd;
}
</style>